import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Input, Select, Button, Table, Modal, Pagination } from 'antd';
import { DEFAULT_PAGE_SIZE, DEFAULT_INVALID_STATE, DEFAULT_VALID_STATE } from '@/constants';
import { CONST_PERMISSION_CODE_UNIT_ADD, CONST_PERMISSION_CODE_UNIT_UPD, CONST_PERMISSION_CODE_UNIT_STOP } from '@/constants';
import styles from './index.less';

import Edit from './edit';

const { Content } = Layout;
const { confirm } = Modal;
const { Option } = Select;

const CONST_MODE_SELECT = 'select';
const CONST_MODE_LIST = 'list';

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'unit';
    const { global, mode } = props;
    const { isAdmin, currentUnit = {} } = global;
    this.state = {
      constants: {
        unitTyps: []
      },
      query: {
        state: DEFAULT_VALID_STATE,
        id: !isAdmin ? currentUnit.id : undefined
      },
      mode: mode || CONST_MODE_LIST
    }
  }

  componentDidMount() {
    const { query = {} } = this.state;

    this.props.dispatch({
      type: 'global/queryConfigDictionary',
      payload: {
        code: 'UNIT_TYPE',
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, unitTyps: data } });
        }
      }
    });
    this.props.dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current: 1,
        pageSize: this.state.mode === CONST_MODE_LIST ? DEFAULT_PAGE_SIZE : DEFAULT_PAGE_SIZE / 2
      }
    });
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增单位', editData: {} }
    })
  }

  detailBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '查看单位', editData: record }
    })
  }

  editBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑单位', editData: record }
    })
  }

  stopBtnClick = (record) => {
    confirm({
      title: '是否确认停用单位?',
      content: Array.isArray(record) ? undefined : `单位 [${record.unit_name}]`,
      onOk: () => {
        const { query = {} } = this.state;
        const { dispatch, modular } = this.props;
        const { current, pageSize } = modular;

        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            data: Array.isArray(record) ? record.map(item => ({ ...item, state: DEFAULT_INVALID_STATE })) : { ...record, state: DEFAULT_INVALID_STATE },
            ...query,
            current,
            pageSize
          }
        });
      },
      onCancel() { },
    });
  }

  searchBtnClick = () => {
    const { query = {} } = this.state;
    const { dispatch, modular } = this.props;
    const { pageSize = DEFAULT_PAGE_SIZE } = modular;

    dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current: 1,
        pageSize
      }
    });
  }

  onChange = (current, pageSize) => {
    const { query = {} } = this.state;
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current,
        pageSize
      }
    })
  }

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize)
  }

  onOk = () => {
    const { query = {} } = this.state;
    const { dispatch, form, modular } = this.props;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields((err, values) => {
      if (!err) {
        const data = {
          ...editData,
          ...values
        };
        if (!editData.id) {
          data.state = DEFAULT_VALID_STATE;
        }
        dispatch({
          type: `${this.modularName}/saveOrUpdateData`,
          payload: {
            data,
            ...query,
            current,
            pageSize
          }
        });
      }
    });
  }

  render() {
    const { constants = {}, query = {}, selectedRows = [], mode } = this.state;
    const { unitTyps = [] } = constants;
    const { dispatch, form, loading, global, modular } = this.props;
    const { userPermissions = [] } = global;
    const { data, current = 1, pageSize = DEFAULT_PAGE_SIZE, total = 0, rowKey, visible, editData = {} } = modular;

    const columns = [
      {
        title: '单位名称',
        dataIndex: 'unit_name',
        ellipsis: true,
        width: 250
      },
      {
        title: '值班地址',
        dataIndex: 'unit_address',
        ellipsis: true,
        width: 350
      },
      {
        title: '单位类型',
        dataIndex: 'unit_type',
        ellipsis: true,
        width: 200,
        render: (text) => {
          const filter = unitTyps.filter(item => item.dicKey === text);
          if (filter && filter.length > 0) {
            return filter[0].dicName;
          }
          return text;
        }
      },
      {
        title: '值班电话',
        dataIndex: 'phone',
        ellipsis: true,
        width: 200,
        render: (text, record) => {
          if (record) {
            return `${record.unit_code ? record.unit_code + '-' : ''}${record.unit_phone || ''}`
          }
          return '-';
        }
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.detailBtnClick.bind(this, record)}>查看</span>
              {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_UNIT_UPD) &&
                <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
              }
              {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_UNIT_STOP) &&
                <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>停用</span>
              }
            </div>
          );
        }
      }
    ];

    return (
      <Layout className={styles.basic_layout_wrapper} style={{ ...this.props.style }}>
        <div className={[styles.conditions_wrapper, mode === CONST_MODE_SELECT ? styles.conditions_no_border_wrapper : null].join(' ')}>
          <Input placeholder='单位名称' style={{ width: 240, marginRight: 16 }} onChange={e => this.setState({ query: { ...query, unit_name: e.target.value || undefined } })} />
          <Select allowClear placeholder='单位类型' style={{ width: 240, marginRight: 16 }} onChange={value => this.setState({ query: { ...query, unit_type: value } })}>
            {unitTyps && unitTyps.map(item => {
              return <Option key={item.dicKey} value={item.dicKey}>{item.dicName}</Option>
            })}
          </Select>
          <Button icon='search' type='primary' onClick={this.searchBtnClick}>搜索</Button>
        </div>
        <Content className={[styles.conditions_wrapper, mode === CONST_MODE_SELECT ? styles.conditions_no_border_wrapper : null].join(' ')} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            {mode === CONST_MODE_LIST &&
              <div>
                {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_UNIT_ADD) &&
                  <Button icon='plus' type='primary' style={{ width: 110, marginRight: 16, marginBottom: 16 }} onClick={this.appendBtnClick}>新增单位</Button>
                }
                {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_UNIT_STOP) &&
                  <Button icon='delete' type='danger' style={{ marginBottom: 16 }} onClick={selectedRows && selectedRows.length > 0 ? this.stopBtnClick.bind(this, selectedRows) : undefined}>批量停用{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
                }
              </div>
            }
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={mode === CONST_MODE_LIST ? columns : columns.slice(0, columns.length - 1)}
                dataSource={data}
                loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                pagination={false}
                rowKey={rowKey}
                rowSelection={
                  mode === CONST_MODE_LIST ?
                    Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_UNIT_STOP) ?
                      {
                        onChange: (selectedRowKeys, rows) => {
                          this.setState({ selectedRows: [...selectedRows.filter(item => selectedRowKeys.includes(item.id) && !rows.map(row => row.id).includes(item.id)), ...rows] })
                        }
                      } : null :
                    { ...this.props.rowSelection }
                }
                scroll={{ x: true }}
              />
            </Content>
            <div style={{ marginTop: 16 }}>
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                showQuickJumper
                showSizeChanger={mode === CONST_MODE_LIST}
                showTotal={(total, range) => `共有 ${total} 条数据`}
                onChange={this.onChange}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          </Layout>
        </Content>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={600}
          okButtonProps={visible === '查看单位' ? { style: { display: 'none' } } : {}}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            })
          }}
        >
          <Edit form={form} constants={constants} data={editData} disabled={visible === '查看单位'} />
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, global, unit }) => ({ loading, global, modular: unit }))(Form.create()(Index));